package com.example.xd.javatest.socket_test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.LinkedList;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

/**
 * @auther XuDan on 2020/7/1.
 * - Step 1：创建ServerSocket对象，绑定监听的端口
 * - Step 2：调用accept()方法监听客户端的请求
 * - Step 3：连接建立后，通过输入流读取客户端发送的请求信息
 * - Step 4：通过输出流向客户端发送响应信息
 * - Step 5：关闭相关资源
 */
public class ServiceSocket {
    private Executor mExecutor = null;
    private LinkedList<Socket> mList = new LinkedList<>();

    public ServiceSocket() throws IOException {
        mExecutor = Executors.newCachedThreadPool();
        ServerSocket serverSocket = new ServerSocket(8888);
        System.out.println("连接前。。。");
        Socket socket = serverSocket.accept();
        mList.add(socket);
        mExecutor.execute(new MyRun(socket));

    }

    class MyRun implements Runnable {

        private Socket mSocket;

        public MyRun(Socket socket) {
            mSocket = socket;
        }

        @Override
        public void run() {
            while (true) {
                InputStream is = null;
                InputStreamReader isr = null;
                BufferedReader br = null;
                OutputStream os = null;
                PrintWriter pw = null;

                try {
                    is = mSocket.getInputStream();//获取输入流
                    isr = new InputStreamReader(is);
                    br = new BufferedReader(isr);
                    String info = br.readLine();
                    while (info != null) {
                        System.out.println("客户端" + mList.size() + ":" + info);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }


            }
        }
    }
}
